# -*- coding: utf8 -*-

from project.mysql.table import Table

class TableImage2Image( Table ):

    _table_name = "image2image"

    def create( self ):
        cur = self.getCursor()

        # Create table
        cur.execute(
            "CREATE TABLE IF NOT EXISTS `%s` (" % self._table_name+
            "id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, "+
            "image1_id INTEGER UNSIGNED NOT NULL, "+
            "image2_id INTEGER UNSIGNED NOT NULL, "+
            "file1_id INTEGER UNSIGNED NOT NULL, "+
            "file2_id INTEGER UNSIGNED NOT NULL, "+
            "equal_proc TINYINT(3) UNSIGNED NOT NULL, "+
            "quality_points TINYINT(2) NOT NULL) ENGINE %s" % self.getEngine()
        )
        try:
            cur.execute(
                "ALTER TABLE `%s` ADD INDEX images (image1_id, image2_id)" % self._table_name
            )
        except:
            pass
        try:
            cur.execute(
                "ALTER TABLE `%s` ADD INDEX files (file1_id, file2_id)" % self._table_name
            )
        except:
            pass
        cur.close()
        return


    def insert( self, image1_id, image2_id, file1_id, file2_id, equal_proc, quality_points):

        cur = self.getCursor()

        image_id = cur.execute(
            "INSERT INTO `%s` (" % self._table_name +
            "image1_id, image2_id, file1_id, file2_id, equal_proc, quality_points" +
            ") VALUES (" +
            "%(image1_id)s, %(image2_id)s, %(file1_id)s, %(file2_id)s, %(equal_proc)s, %(quality_points)s" +
            ")",
            {
                "image1_id": image1_id,
                "image2_id": image2_id,
                "file1_id": file1_id,
                "file2_id": file2_id,
                "equal_proc": equal_proc,
                "quality_points": quality_points
            }
        )
        self.getConnection().commit()

        cur.close()
        return image_id

    def has(self, image1_id, image2_id):
        cur = self.getCursor()
        cur.execute(
            "SELECT * FROM `%s` WHERE" % self._table_name +
            " (image1_id=%(id1)s AND image2_id=%(id2)s) OR (image1_id=%(id2)s AND image2_id=%(id1)s)",
            {
                "id1": image1_id,
                "id2": image2_id
            }
        )
        item = cur.fetchone()
        cur.close()
        if not item:
            item = False
        return item

    def remove_file(self, file_id):
        cur = self.getCursor()
        rc = cur.execute(
            "DELETE FROM `%s` " % self._table_name +
            "WHERE file1_id=%(id)s OR file2_id=%(id)s",
            {
                "id": file_id
            }
        )
        self.getConnection().commit()
        cur.close()
        return rc

    pass
